package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.constants.behavior.BehaviorConstants;
import com.heima.common.constants.mess.app.UpdateArticleMess;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Resource
    ApBehaviorEntryService behaviorEntryService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null){
//            用户已登录，使用userId
            ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry == null){
                log.error("like 1  获取用户行为实体失败,userID为{},equipmentId为{}",user.getId(),dto.getEquipmentId());
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            return operationLike(behaviorEntry,dto);
        }
//        用户未登录,使用设备ID
        ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        if (behaviorEntry == null){
            log.error("like 3  获取用户行为实体失败,userID为{},equipmentId为{}",null,dto.getEquipmentId());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return  operationLike(behaviorEntry,dto);
    }

    @Override
    public Boolean check(ApBehaviorEntry behaviorEntry, Long articleId) {
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(articleId));
        ApLikesBehavior like = mongoTemplate.findOne(query, ApLikesBehavior.class);
        if (like == null){
            return false;
        }
        return true;
    }

    private ResponseResult operationLike(ApBehaviorEntry behaviorEntry,LikesBehaviorDTO dto) {
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        Short type = dto.getType();
        Short operation = dto.getOperation();
        Long articleId = dto.getArticleId();
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(articleId));
//        ApLikesBehavior like = null;
        ApLikesBehavior like = mongoTemplate.findOne(query, ApLikesBehavior.class);
        if (like == null){
//                无记录且行为是0则新增点赞记录
            if (BehaviorConstants.ONE.equals(operation)){
                log.error("重复操作");
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            like = new ApLikesBehavior();
//            like.setType(type);
            like.setArticleId(articleId);
            like.setOperation(operation);
            like.setCreatedTime(new Date());
            like.setEntryId(behaviorEntry.getId());
            like = mongoTemplate.save(like);

//            点赞成功,发送消息给MQ

            updateArticleMess.setArticleId(like.getArticleId());
            updateArticleMess.setAdd(1);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
//                有记录则检查是否为重复操作
            if (BehaviorConstants.ZERO.equals(operation)){
                log.error("重复操作");
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
//                没有重复操作则删除记录
            mongoTemplate.remove(query,ApLikesBehavior.class);

//            取消点赞成功,发送消息给MQ
            updateArticleMess.setArticleId(like.getArticleId());
            updateArticleMess.setAdd(-1);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

    }

}
